# -*- coding: utf-8 -*-
# @Time    : 2020/5/15 11:16
# @Author  : suhong
# @File    : save_routers.py
# @Software: PyCharm
from fastapi import APIRouter
from tortoise.contrib.fastapi import HTTPNotFoundError

from app.allsubdb.jss_wf.models import CheckDetailNum_Pydantic, CheckDetailNum, MgIdNum_Pydantic,MgIdNum,PageNum,PageNum_Pydantic

router = APIRouter()

# DetailId
@router.post("/insert/mg_id_num")
async def create_user(mgid: MgIdNum_Pydantic):
    user_obj = await MgIdNum.create(**mgid.dict(exclude_unset=True))
    return await MgIdNum_Pydantic.from_tortoise_orm(user_obj)

@router.get("/get/mg_id_num/{stat}",  responses={404: {"model": HTTPNotFoundError}})
async def get_user(stat : int):
    return await MgIdNum_Pydantic.from_queryset(MgIdNum.filter(stat=stat).limit(10000))


@router.post("/update/mg_id_num", response_model=MgIdNum_Pydantic, responses={404: {"model": HTTPNotFoundError}})
async def update_user(id_: str, user: MgIdNum_Pydantic):
    user_dict =user.dict(exclude_unset=True)
    del user_dict["id_"]
    await MgIdNum.filter(id_=id_).update(**user_dict)
    return await MgIdNum_Pydantic.from_queryset_single(MgIdNum.get(id_=id_))


# check_detail_num
@router.post("/insert/check_detail_num")
async def create_user(check: CheckDetailNum_Pydantic):
    try:
        await CheckDetailNum_Pydantic.from_queryset_single(CheckDetailNum.get(key=check.key))
        return ""
    except:
        user_obj = await CheckDetailNum.create(**check.dict(exclude_unset=True))
        return await CheckDetailNum_Pydantic.from_tortoise_orm(user_obj)

@router.post("/update/check_detail_num", response_model=CheckDetailNum_Pydantic, responses={404: {"model": HTTPNotFoundError}})
async def update_user(key: str, user: CheckDetailNum_Pydantic):
    user_dict =user.dict(exclude_unset=True)
    del user_dict["key"]
    await CheckDetailNum.filter(key=key).update(**user_dict)
    return await CheckDetailNum_Pydantic.from_queryset_single(CheckDetailNum.get(key=key))

@router.get("/get/check_detail_num/{key}", response_model=CheckDetailNum_Pydantic, responses={404: {"model": HTTPNotFoundError}})
async def get_user(key: str):
    return await CheckDetailNum_Pydantic.from_queryset_single(CheckDetailNum.get(key=key))

# pagess_num
@router.post("/update/pagess_num", response_model=PageNum_Pydantic, responses={404: {"model": HTTPNotFoundError}})
async def update_user(user: PageNum_Pydantic):
    user_dict =user.dict(exclude_unset=True)
    cid_pagenum = user_dict["cid_pagenum"]
    del user_dict["cid_pagenum"]
    await PageNum.filter(cid_pagenum=cid_pagenum).update(**user_dict)
    return await PageNum_Pydantic.from_queryset_single(PageNum.get(cid_pagenum=cid_pagenum))

